﻿namespace WCBG.ToolsForUnity.Tools
{
    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;

    public class FEnumUtil
    {
        public static string GetEnumDescription<T>(T enumVal)
        {
            string name = enumVal.ToString();
            DescriptionAttribute[] customAttributes = (DescriptionAttribute[]) enumVal.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (customAttributes.Length != 0)
            {
                return customAttributes[0].Description;
            }
            return name;
        }

        public static int Length<T>() => 
            Enum.GetValues(typeof(T)).Length;

        public static T Parse<T>(string str) => 
            ((T) Enum.Parse(typeof(T), str));

        public static T SafeParse<T>(string str)
        {
            try
            {
                return (T) Enum.Parse(typeof(T), str);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        public static bool TryCast<T>(object inVal, out T outVal)
        {
            outVal = default(T);
            try
            {
                outVal = (T) inVal;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

